﻿using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;
using DingTalkAPIHelp.Base;
using System;
using System.IO;
using Top.Api.Util;

namespace DingTalkAPIHelp.File
{
    public class DingPanFile : SysConfigManager
    {
        public delegate void FileUploadArg(FileUploadLog log);
        public event FileUploadArg UploadChangeEvent;

        public void MiniFileUpload(string filepath)
        {
            FileUploadLog log = new FileUploadLog()
            {
                Status = FileUploadStatus.StartUpload,
                LogText = "准备开始上传...",
                LogTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                Progress = 0,
                ResultState = true,
            };
            if (UploadChangeEvent != null) UploadChangeEvent(log);

            FileInfo file = new FileInfo(filepath);
            OapiFileUploadSingleRequest request = new OapiFileUploadSingleRequest();
            request.FileSize = file.Length;
            request.AgentId = AgentId.ToString();
 
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/file/upload/single?" + WebUtils.BuildQuery(request.GetParameters()));
            // 必须重新new一个请求
            request = new OapiFileUploadSingleRequest();
            request.File = new FileItem(file);
            OapiFileUploadSingleResponse response = client.Execute(request, accessToken);

            FileUploadLog log2 = new FileUploadLog()
            {
                Status = FileUploadStatus.UploadEnd,
                LogText = response.IsError? response.ErrMsg: "文件上传成功:" + response.Body,
                LogTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                Progress = 100,
                ResultState = !response.IsError,
            };
 
            if (UploadChangeEvent != null) UploadChangeEvent(log2);
        }
    }

    /// <summary>
    /// 文件上传LOG日志
    /// </summary>
    public class FileUploadLog
    {
        /// <summary>
        /// 上传状态
        /// </summary>
        public FileUploadStatus Status { get; set; }
        /// <summary>
        /// 上传进度
        /// </summary>
        public double Progress { get; set; }
        /// <summary>
        /// 当前结果状态
        /// </summary>
        public bool ResultState { get; set; }
        /// <summary>
        /// 日志内容
        /// </summary>
        public string LogText { get; set; }
        /// <summary>
        /// 日志时间
        /// </summary>
        public string LogTime { get; set; }
    }
    public enum FileUploadStatus
    {
        StartUpload,
        Uploading,
        UploadEnd
    }
}
